package org.nuist.config;


import com.alibaba.fastjson.JSONObject;
import org.nuist.pojo.VirtualMachine;
import org.nuist.service.virtualmachine.VirtualMachineServiceImpl;
import org.nuist.utils.ShellTool.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class MyStartupRunner implements CommandLineRunner {

    @Autowired
    VirtualMachineServiceImpl virtualMachineService;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("服务启动执行,执行加载数据操作");

        //执行封装过的shell命令
        Function function=new Function();
        JSONObject jsonObject = function.listVM();

        List<Map> jsonObjects= (List<Map>) jsonObject.get("VMLISTS");

        System.out.println(jsonObjects);

        for (Map map : jsonObjects) {

            VirtualMachine vm=new VirtualMachine();

            String port=(String) map.get("VMID");

            try {
                //如果在数据库中找不到虚拟机
                if (virtualMachineService.findVirtualMachineByPort(port) == null) {

                    //端口号和VMID一致
                    vm.setPort((String) map.get("VMID"));

                    //ip和NAME保持一致
                    vm.setIp((String) map.get("NAME"));
                    vm.setStatus((String) map.get("STATUS"));

                    vm.setMem(Integer.parseInt((String) map.get("MEM")));
                    vm.setOccupied(false);
                    vm.setBootDisk(Double.parseDouble((String) map.get("BOOTDISK")));

                    //保存虚拟机
                    virtualMachineService.save(vm);

                }
            }catch (Exception e){
                //pass
            }

        }

        System.out.println("OK!");

    }


}
